package com.mq.exchange;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

import java.util.Random;
import java.util.concurrent.TimeoutException;

/**
 * 发布订阅:扇出交换
 *
 * @author xwj
 * @date 2019/2/28
 */
public class EmitLogFanout {
    /**
     * 交换机名称
     */
    private static final String EXCHANGE_NAME = "logs";

    public static void main(String[] argv)
            throws java.io.IOException, TimeoutException {

        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("localhost");
        Connection connection = factory.newConnection();
        Channel channel = connection.createChannel();

        // 声明交换机
        // fanout:扇出，向所有的queue广播所有收到的消息
        // fanout类型：简单的广播消息
        channel.exchangeDeclare(EXCHANGE_NAME, "fanout");

        String message = getMessage();

        channel.basicPublish(EXCHANGE_NAME, "", null, message.getBytes());
        System.out.println("Send log:" + message);

        channel.close();
        connection.close();
    }

    private static String getMessage() {
        Random random = new Random();
        int taskTime = random.nextInt(5) + 1;
        StringBuilder msg = new StringBuilder();
        for (int i = 0; i < taskTime; i++) {
            msg.append(".");
        }
        return msg.toString();
    }
}

